package com.nsgf.library.ui.page;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.Nullable;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.MainNsgfActivity;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.utils.BaseAlterDialog;
import com.nsgf.library.utils.SPUtil;
import com.nsgf.library.utils.ToastUtils;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.DialogLoginTypeDataBinding;
import com.zhht.htzx.databinding.FragmentLoginBinding;
import com.zhht.htzx.ui.SettleActivity;

import org.greenrobot.eventbus.EventBus;


public class LoginActivity extends BaseActivity {
    private LoginStates mStates;

    private LoginDialogStates mDialogStates;
    private FragmentLoginBinding mBinding;
    private AccountRequester mAccountRequester;
    DialogLoginTypeDataBinding binding;
    private Dialog dialog;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(LoginStates.class);
        mDialogStates = getActivityScopeViewModel(LoginDialogStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);

    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.fragment_login, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (FragmentLoginBinding) getBinding();

        mStates.titleBar.set("登录");
        getLifecycle().addObserver(mAccountRequester);

        mBinding.toggleButtonShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 切换为可见密码
                    mBinding.etLoginPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    // 切换为不可见密码
                    mBinding.etLoginPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }

                // 设置光标位置到末尾
                mBinding.etLoginPass.setSelection(mBinding.etLoginPass.getText().length());
            }
        });
        mAccountRequester.getUserDataResult().observe(this, dataResult -> {

            if (0 == dataResult.getResponseCode()) {
                UserInfo.getInstance().setTokenValue(dataResult.getData().getAccessToken());
                UserInfo.getInstance().setId(String.valueOf(dataResult.getData().getUserId()));
                UserInfo.getInstance().setIsMerchant(dataResult.getData().getIsMerchant());
                UserInfo.getInstance().setReceiveStatus(dataResult.getData().getReceiveStatus());
                EventMsg message=new EventMsg();
                message.setMsg("dialog");
                EventBus.getDefault().post(message);
                finish();

            } else {
                getController().dismissLoading();
                new BaseAlterDialog(this, R.style.dialogstyle,
                        dataResult.getMsg(), "确定", "登录失败",
                        (dialog, confirm) -> {
                            dialog.dismiss();

                        }).show();
            }
        });
        mStates.name.set(SPUtil.get("userName", "", LoginActivity.this));
        mStates.password.set(SPUtil.get("userPassword", "", LoginActivity.this));
    }

    public static class LoginStates extends StateHolder {

        public final State<String> name = new State<>("");

        public final State<String> password = new State<>("");

        public final State<Boolean> checkAgreement= new State<>(false);

        public final State<Boolean> loadingVisible = new State<>(false);

    }

    public static class LoginDialogStates extends StateHolder {

        public final State<String> name = new State<>("");

    }


    public class ClickProxy {

        public void login() {

            //TODO tip 5：通过双向绑定，使能通过 state-ViewModel 中与 xml 控件发生绑定的"可观察数据" 拿到控件数据，
            // 避免直接接触控件实例而埋下 Null 安全一致性隐患。

            if (!mStates.checkAgreement.get()){
                ToastUtils.showShortToast("请勾选用户协议与隐私政策");
                return;
            }

            if (TextUtils.isEmpty(mStates.name.get()) || TextUtils.isEmpty(mStates.password.get())) {

                new BaseAlterDialog(LoginActivity.this, R.style.dialogstyle,
                        getString(R.string.username_or_pwd_incomplete), "确定", "登录失败",
                        (dialog, confirm) -> {
                            dialog.dismiss();

                        }).show();
                return;
            }

            getController().displayLoading();

            mAccountRequester.loginCode(mStates.name.get(), mStates.password.get());
            mStates.loadingVisible.set(true);

        }

        public void openWebView(){

            startActivity(new Intent()
                    .putExtra("id", String.valueOf(2))
                    .putExtra("title", "用户协议")
                    .setClass(LoginActivity.this, WebViewApiActivity.class));
        }

        public void codeLogin() {
            loginStatus(false);
        }

        public void passLogin() {
            loginStatus(true);
        }

        public void sendCode() {
            if (TextUtils.isEmpty(mStates.name.get())) {
                ToastUtils.showLongToast(getString(R.string.username_or_pwd_incomplete));
                return;
            }
            mAccountRequester.sendCode(mStates.name.get(),1);
            timer.start();
        }
    }


    public class DialogClickProxy {
        public void cancel() {
            dialog.dismiss();
        }

        public void clickSing() {
            binding.ivUserTypeSing.setAlpha(1f);
            binding.tvUserTypeSing.setAlpha(1f);
            binding.ivUserTypeMore.setAlpha(0.6f);
            binding.tvUserTypeMore.setAlpha(0.6f);
        }

        public void clickMore() {
            binding.ivUserTypeSing.setAlpha(0.6f);
            binding.tvUserTypeSing.setAlpha(0.6f);
            binding.ivUserTypeMore.setAlpha(1f);
            binding.tvUserTypeMore.setAlpha(1f);
        }

        public void confirm() {
            startActivity(new Intent().setClass(LoginActivity.this, MainNsgfActivity.class));
            UserInfo.getInstance().setActivityType("mainActivity");
            dialog.dismiss();
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    /**
     * 是否账号密码登录
     *
     * @param status
     */
    private void loginStatus(boolean status) {

        if (status) {
            mBinding.etLoginPass.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
            mBinding.etLoginPass.setHint("请输入密码");
        } else {
            mBinding.etLoginPass.setInputType(InputType.TYPE_CLASS_NUMBER);
            mBinding.etLoginPass.setHint("请输入验证码");
        }
        mBinding.tvSendLoginCode.setVisibility(!status ? View.VISIBLE : View.GONE);
        mBinding.tvLoginCode.setVisibility(status ? View.VISIBLE : View.GONE);
        mBinding.tvLoginPass.setVisibility(!status ? View.VISIBLE : View.GONE);
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mBinding.tvSendLoginCode.setText(millisUntilFinished / 1000 + "秒");
            mBinding.tvSendLoginCode.setTextColor(Color.parseColor("#999999"));
        }

        @Override
        public void onFinish() {
            mBinding.etLoginPass.requestFocus();
            mBinding.tvSendLoginCode.setText("重新获取");
            mBinding.tvSendLoginCode.setClickable(true);
            mBinding.tvSendLoginCode.setTextColor(Color.parseColor("#165dff"));
        }
    };
}
